import requests

from config import WXCORPID, WXSERET, WXAGENTID


class QyWxApp:
    corpid = WXCORPID  # 企业id
    secret = WXSERET  # 应用秘钥
    agentid = WXAGENTID  # 应用id

    @classmethod
    def get_access_token(cls):
        """
        获取接口调用凭证
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}"
        url = url.format(cls.corpid, cls.secret)
        res = requests.get(url)
        access_token = ""
        if res.status_code == 200:
            res_data = res.json()
            access_token = res_data['access_token']
        return access_token

    @staticmethod
    def get_code_to_user(access_token, code):
        """
        获取企业微信code，查询访问用户
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token={}&code={}".format(access_token, code)
        res = requests.get(url)
        return res.json()

    @staticmethod
    def get_user_detail(access_token, user_ticket):
        """
        根据user_ticket，获取用户敏感数据
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token={}".format(access_token)
        data = {"user_ticket": user_ticket}
        res = requests.post(url, json=data)
        res_data = res.json()
        return res_data

    @staticmethod
    def get_id_to_user(access_token, user_id):
        """
        根据用户id，查询访问用户
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={}&userid={}".format(access_token, user_id)
        res = requests.get(url)
        return res.json()

    @classmethod
    def send_msg(cls, access_token, touser, content):
        """
        应用发送文本消息
        """
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(access_token)
        data = {
            "touser": touser,  # @all发给所有人；发送多人使用|分割
            "msgtype": "text",
            "agentid": cls.agentid,
            "text": {
                "content": content
            }
        }
        res = requests.post(url, json=data)
        res_data = res.json()
        # print(res, res_data)
        return res_data


if __name__ == '__main__':
    token = QyWxApp().get_access_token()
    user_info = QyWxApp.send_msg(token, 'xinyu.zhang', "合同还有三小时过期")
    print('888', user_info)

